package models

import (
	"gorm.io/gorm"
	"go_part/utils"
	"fmt"
)

type Community struct {
	gorm.Model
	Name string
	OwnerId uint 
	Img string
	Desc string
}

func CreateCommunity(community Community) (int,string) {
	if len(community.Name) == 0 {
		return -1,"群名称不能为空"
	}

	if community.OwnerId==0 {
		return -1,"请先登录"
	}

	if err := utils.DB.Create(&community).Error; err != nil {
		fmt.Println(err)
		return -1,"建群失败"
	}

	return 0,"建群成功"
}

func LoadCommunity(owner_id uint) ([]*Community,string){
	data := make([]*Community,10)
	utils.DB.Where("owner_id =?",owner_id).Find(&data)
	for _, v := range data {
		fmt.Println(v)
	}
	return data,"查询成功"
}

func JoinGroup(userId uint, comId uint)(int, string){
	contact := Contact{}
	contact.OwnerId = userId
	contact.TargetId = comId
	contact.Type = 2
	community := Community{}

	utils.DB.Where("id=? or name=?",comId, comId ).Find(&community)
	if community.Name == "" {
		return -1,"没有找到该群"
	}
	utils.DB.Where("owner_id=? and target_id=? and type =2",userId, comId).Find(&contact)
	if !contact.CreatedAt.IsZero() {
		return -1,"已加过此群"
	}else{
		utils.DB.Create(&contact)
		return -1,"加群成功"
	}


}